import IconFont from '@/components/IconFont';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import CommonTextarea from '@/pages/OrderModule/common/components/CommonTextarea';
import { union } from "lodash";
import { Form } from 'antd';
import { useState } from 'react';

/**
 * 批量输入弹窗
 */
const BatchInputModal = (props) => {
  const { value, onChange, children, title = '批量输入', maxCount=500, placeholder } = props;
  const [inputValue, setInputValue] = useState(value);

  const [show, toggleShow] = useState(false);
  const [form] = Form.useForm();

  const btn = children || <IconFont style={{ fontSize: '12px', cursor: 'pointer' }} type="icondirect-input"></IconFont>;

  const openModal = () => {
    toggleShow(true);
    setInputValue(formatBatchInput(props.value));
  };

  const closeModal = () => {
    toggleShow(false);
  };

  const formatBatchInput = (value) => {
    // 逗号变换为换行符
    // 处理边界情况,多个连续的逗号，只保留一个
    return value?.replace(/,/g, '\n').replace(/\n+/g, '\n');
  };

  const formatBatchOutput = (value) => {
    // 换行符变换为逗号
    // 处理边界情况,多个连续的换行符，只保留一个
    const arr = value.split(/\n|,|，/gi).filter(item => item.replace(/ /g, ""));
    const item = union(arr.slice(0, maxCount)).join(",");
    return item;
  };

  return (
    <>
      <span onClick={openModal}>{btn}</span>
      <CommonModal
        title={{ title }}
        open={show}
        onCancel={closeModal}
        width={600}
        destroyOnClose
        onOk={(e) => {
          onChange?.(formatBatchOutput(inputValue));
          closeModal();
        }}
      >
        <CommonTextarea value={inputValue} placeholder={placeholder} style={{ minHeight: 200 }} onChange={(e) => setInputValue(e.target.value)}></CommonTextarea>
      </CommonModal>
    </>
  );
};

export default BatchInputModal;
